package io.mft.datasource.mq.container;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import io.mft.commons.config.datasource.DSConfigSource;
import io.mft.commons.config.mq.MqConfig.ConfigValue;
import io.mft.commons.function.response.kv.KVMap;
import io.mft.datasource.mq.container.impl.RabbitMqContainer;
import io.mft.datasource.mq.rabbitmq.MqDatasource;

public class MqContainerManager {
	private static MqContainerManager instance = new MqContainerManager();

	public static MqContainerManager getInstance() {
		return instance;
	}

	Map<MqContainerType, MqContainer> containerMap=new HashMap<MqContainerType, MqContainer>();
	private MqContainerManager() {
		containerMap.put(MqContainerType.rabbitmq, new RabbitMqContainer());
	}

	public void init(MqContainerType mqContainerType,DSConfigSource dsConfigSource) {
		if (dsConfigSource==null) {
			return;
		}
		dsConfigSource.getDatasources().forEach(da -> {
			MqDatasource datasource = BeanUtil.mapToBean(da.getConfig(), MqDatasource.class, false);
			datasource.setId(da.getId());
			datasource.setDesc(da.getDesc());
			MqContainer container=containerMap.get(mqContainerType);
			container.AddMqDatasource(datasource);
		});
	}
	public void init(String pluginId,MqContainerType mqContainerType,ConfigValue configValue) {
		if (configValue==null) {
			return ;
		}
		MqContainer container=containerMap.get(mqContainerType);
		if (configValue.getQueues() != null) {
			configValue.getQueues().forEach(q -> {
				container.addMqQueue(pluginId,q);
			});
		}

		if (configValue.getExchanges() != null) {
			configValue.getExchanges().forEach(ex -> {
				container.addMqExchange(pluginId,ex);
			});
		}
		if (configValue.getConsumers() != null) {
			configValue.getConsumers().forEach(c -> {
				container.addMqConsumer(pluginId,c);
			});
		}
	}
	public  void sendMessage(MqContainerType mqContainerType,String pluginId,String exchangeId,KVMap message) {
		MqContainer container=containerMap.get(mqContainerType);
		container.sendMessage(pluginId,exchangeId, message);
	}
	
}
